package com.example.recharge;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class three0 extends AppCompatActivity implements View.OnClickListener{
    private Context mContext;
    private  ListView listView;
    private TextView wifi;
    private LinearLayout colorback;
    private List<four0>four0s=new ArrayList<>();
    private Button batch_recharge;
    private Button Record;
    private CheckBox frame;
    private Context activity;
    private List<Integer> checkBoxIDList = new ArrayList<>();//存储checkBox的值
   private StringBuilder list2 = new StringBuilder();
    private StringBuilder list1 = new StringBuilder();
   int o;
    @SuppressLint("WrongViewCast")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.four);
        listView=findViewById(R.id.lv);
        batch_recharge=findViewById(R.id.batch_recharge);
        mContext=this;
        colorback=(LinearLayout)findViewById(R.id.colorback);
        Record=(Button)findViewById(R.id.Recharge_record);
        Record.setOnClickListener(this);
        sedRequestWithOkHttp();
    }
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                Toast.makeText(context, "网络通信状态:有网", Toast.LENGTH_SHORT).show();
            } else{
                Toast.makeText(context, "网络通信状态:无信号", Toast.LENGTH_SHORT).show();
            }
        }
        return false;
    }
    @Override
    public void onClick(View view) {
        //跳转页面
        startActivity(new Intent(three0.this,recharge_record.class));
    }
    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG","2354"+response);
                Gson gson=new Gson();
                four0 carList = gson.fromJson(response, four0.class);
                four0s.add(carList);
                listView.setAdapter(new MyAdapter(four0s));

            }
        });
    }
    private void sedRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client=new OkHttpClient();
                    Request request=new Request.Builder()
                            .url("http://hh1.me:5001/carlist")
                            .build();
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    Log.i("tag",responseData+"www");
                    showResponse(responseData);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    class MyAdapter extends BaseAdapter{
        List<four0> four;
        private Context activity;

        public MyAdapter(List<four0> four00s) {
            four=four00s;
        }

        @Override
        //告诉集合要显示多少数据
        public int getCount() {
            return  four.get(0).getData().size();
        }
        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }
        @Override
        //告诉listview每个条目显示的内容
        public View getView(final int i, View view, ViewGroup viewGroup) {
            View view1=View.inflate(three0.this,R.layout.three,null);
            TextView num=view1.findViewById(R.id.tv0000);
            final TextView cz=view1.findViewById(R.id.tv1111);
            final CheckBox fxk=view1.findViewById(R.id.frame);
            LinearLayout colorback=view1.findViewById(R.id.colorback);
            final TextView cp = view1.findViewById(R.id.tv2222);
            CheckBox cbox=view1.findViewById(R.id.frame);
            //Button plcz=view1.findViewById(R.id.batch_recharge);
            TextView ye=view1.findViewById(R.id.tv3333);
            Button an=view1.findViewById(R.id.bu0000);
            num.setText(i+1+"");
            cz.setText("车主:"+four.get(0).getData().get(i).getWho());
            cp.setText(four.get(0).getData().get(i).getCarno());
            ye.setText("余额:"+four.get(0).getData().get(i).getAmount());
            if(four.get(0).getData().get(i).getAmount()<=4000){
                colorback.setBackgroundColor(Color.parseColor("#ed1941"));
            }
            an.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showSetDeBugDialog(i,four);
                    isNetworkConnected(mContext);
                    o=1;
                }
            });
            //获取复选框选中状态改变事件进行增删改
            cbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    /** b=选中状态
                     * if b = true 将值添加至checkBoxIDList
                     * if b = false 将值从checkBoxIDList移除
                     * */
                    if (b){
                        checkBoxIDList.add(i);
                        list2.append(cp.getText().toString());
                        list1.append(cz.getText().toString());
                        list2.append("|");
                    }else{
                        checkBoxIDList.remove(new Integer(i));
                    }
                }
            });
            //批量充值
            batch_recharge.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    o=2;
                    showSetDeBugDialog(i,four);
                        Log.v("TAG","ppp"+list2);
//                        list1.append(four.get(0).getData().get(checkBoxIDList.get(i)).getWho());
//                        Log.v("TAG","ooo"+list1);
                }
            });
            return view1;
        }
        //————————————————————————————————————————
        private   void showSetDeBugDialog(final int i, final List<four0> four  ){
            AlertDialog.Builder setDeBugDialog=new AlertDialog.Builder(mContext);
            //获取界面
            final View dialogView= LayoutInflater.from(mContext).inflate(R.layout.five,null);
            final EditText et00000=dialogView.findViewById(R.id.et00000);
            //判断输入款输入的数值是否以0开头
            et00000.addTextChangedListener(mTextWatcher);
            final String je=et00000.getText().toString().trim();
            //将界面填充到AlertDiaLog容器
            setDeBugDialog.setView(dialogView);
            //初始化控件
            TextView cph=(TextView) dialogView.findViewById(R.id.cph);
            final  AlertDialog customAlert=setDeBugDialog.show();
            final Button bu00000=(Button) dialogView.findViewById(R.id.bu00000);
            bu00000.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Toast.makeText(three0.this,"sssss",Toast.LENGTH_SHORT).show();
                    if (o==1){
                        tangchuang(et00000.getText().toString().trim(),four.get(0).getData().get(i).getCarno(),four.get(0).getData().get(i).getWho());
                        customAlert.dismiss();
                        startActivity(new Intent(three0.this,three0.class));
                    }else {
                        for(int k=0;k<checkBoxIDList.size();k++){
                            tangchuang(et00000.getText().toString().trim(),four.get(0).getData().get(checkBoxIDList.get(k)).getCarno(),four.get(0).getData().get(checkBoxIDList.get(k)).getWho());
                            customAlert.dismiss();
                            startActivity(new Intent(three0.this,three0.class));
                        }
                    }

                }
            });
            //  取消点击外部消失弹窗
            setDeBugDialog.setCancelable(false);
            //创建AlertDialog
            setDeBugDialog.create();
            //设置车牌号
            if (o==1){
                cph.setText(four.get(0).getData().get(i).getCarno());
            }else {
                cph.setText(list2.toString());
                list2.delete(0,list2.length());
            }
            //AlertDialog显示cph
            //取消按钮
            dialogView.findViewById(R.id.bu11111).setOnClickListener(new View.OnClickListener() {
                //设置自定义页面的点击逻辑
                @Override
                public void onClick(View view) {
                    customAlert.dismiss();
                }
            });
        }
        //充值不能以0开头
       private TextWatcher mTextWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String text= s.toString();
                int len=s.toString().length();
                if (len==1 && text.equals("0")){
                    s.clear();
                    Toast.makeText(mContext,"金额不能以0开头，请重新输入",Toast.LENGTH_LONG).show();
                }
            }
        };
        private void tangchuang(final String je,final String car,final String cz){
            Log.i("TAG","run333"+je+"ttt"+car+"lll"+cz);
            if (TextUtils.isEmpty(je)){
                Toast.makeText(mContext, "充值金额不能为空", Toast.LENGTH_SHORT).show();
            }else{

                Toast.makeText(mContext,"充值成功",Toast.LENGTH_SHORT).show();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpClient client=new OkHttpClient();
                    MediaType mediaType=MediaType.parse("application/json;charset=UTF-8");
                    String post="{\"who\":\""+cz+"\",\"carno\":\""+car+"\",\"amount\":\""+je+"\"}";
                    Log.i("TAG","run"+post);
                    RequestBody requestBody=RequestBody.create(post,mediaType);
                    /*sedRequestWithOkHttp();*/
                    final Request request=new Request.Builder()
                            .post(requestBody)
                            .url("http://hh1.me:5001/charge")
                            .build();
                    try {
                        final Response response = client.newCall(request).execute();
                        /*final String Sting=;*/
                        Log.d("userinfo",response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
